package com.xiaoxiong.text;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaoxiong.adapter.AttendanceInfoAdapter;
import com.xiaoxiong.bean.AttendanceData;
import com.xiaoxiong.database.OperateFormAttendanceInfo;
import com.xiaoxiong.mlistview.PullDownListView;
import com.xiaoxiong.mlistview.PullDownListView.OnRefreshListener;

/**
 * 
 * @ClassName: AttendanceActivity 
 * @Description: 考勤信息的Activity
 * @author smile
 * @date 2016年5月5日 上午9:35:04 
 *
 */
public class AttendanceActivity extends BaseActivity implements
		OnClickListener, OnRefreshListener {

	/**
	 * 临时保存考勤信息的list
	 */
	private List<AttendanceData> attendancedatas;
	/**
	 * 显示考勤信息的listview的设配器
	 */
	private AttendanceInfoAdapter attendanceInfoAdapter;
	/**
	 * 具有下拉刷新功能的listview
	 */
	private PullDownListView myListView;
	/**
	 * 返回按钮
	 */
	private TextView back;
	/**
	 * 请求地址
	 */
	private String Url;
	/**
	 * 保存获取学生id用到
	 */
	private SharedPreferences post_message;
	/**
	 * 保存获取信息用到
	 */
	private SharedPreferences nb_school_message;
	/**
	 * 加载中的对话框
	 */
	private LoadingDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.stu_attendance);

		judge();
		initData();
		GetInfo();
	}

	// 判断是不是第一次进入该界面
	private void judge() {
		nb_school_message = this.getSharedPreferences("test",
				Context.MODE_PRIVATE);
		boolean is = nb_school_message.getBoolean("isFinAttend", true);
		if (true) {
			dialog = new LoadingDialog(this, "\n第一次进入无信息\n导入中。。。");
			dialog.setCanceledOnTouchOutside(false);
			dialog.show();
			String nowUsername = "你的学号";
			String nowPassword = "你的密码";
			new LoginServer(this, loginHandler, nb_school_message, nowUsername,
					nowPassword).doLogin();
		}
	}

	private void initData() {
		post_message = getSharedPreferences("postload", Context.MODE_PRIVATE);
		//这里获取地址+学生id，下拉刷新时用到
		Url = SchoolUrl.Attendance
				+ post_message.getString("attendanceid", null);

		myListView = (PullDownListView) findViewById(R.id.mlv_attendinfo);
		back = (TextView) findViewById(R.id.back);
		back.setOnClickListener(this);
		attendancedatas = new ArrayList<AttendanceData>();
		attendanceInfoAdapter = new AttendanceInfoAdapter(attendancedatas, this);
		myListView.setAdapter(attendanceInfoAdapter);
		//设置下拉刷新监听
		myListView.setonRefreshListener(this);
	}

	/**
	 * 
	* @Title: GetInfo 
	* @Description: 在本地获取考勤信息
	* @param 
	* @return void
	* @throws
	 */
	private void GetInfo() {

		attendancedatas.clear();
		OperateFormAttendanceInfo ofpi = new OperateFormAttendanceInfo(this);
		Cursor attendancedata = ofpi.queryAttendanceInfo();
		while (attendancedata.moveToNext()) {
			AttendanceData PersonInfoData = new AttendanceData(
					attendancedata.getString(attendancedata
							.getColumnIndex("course_code")),
					attendancedata.getString(attendancedata
							.getColumnIndex("course_name")),
					attendancedata.getString(attendancedata
							.getColumnIndex("attendance_info")));
			attendancedatas.add(PersonInfoData);
		}
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.back:
			//返回按钮点击事件
			AttendanceActivity.this.finish();
			break;
		}
	}

	/**
	 * (non-Javadoc) 
	 * <p>Title: onRefresh</p> 
	 * <p>Description: 下拉刷新调用的方法</p>  
	 * @see com.xiaoxiong.mlistview.PullDownListView.OnRefreshListener#onRefresh()
	 */
	@Override
	public void onRefresh() {

		String nowUsername = "你的学号";
		String nowPassword = "你的密码";
		//重新请求，刷新数据
		new LoginServer(this, loginHandler, nb_school_message, nowUsername,
				nowPassword).doLogin();

	}

	// 登录返回的handler
	@SuppressLint("HandlerLeak")
	private Handler loginHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			Bundle bundle = msg.getData();
			boolean isLogin = bundle.getBoolean("isSuccess");
			if (isLogin) {

				//获取考情信息
				new GetAttendanceInfo(getApplicationContext(),
						attendanceHandler).Post();
			} else {
				if (dialog != null) {
					dialog.dismiss();
				}
				//无论请求成功还是失败都要告诉listview，刷新完成了，才可以隐藏掉头部刷新的效果
				myListView.onRefreshComplete();
				Toast.makeText(getApplicationContext(), "请求失败，请检测你的网络", Toast.LENGTH_SHORT)
						.show();
			}
		}
	};

	@SuppressLint("HandlerLeak")
	private Handler attendanceHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			Bundle bundle = msg.getData();
			String response = bundle.getString("Value");
			boolean hadGetPerson = bundle.getBoolean("isSuccess");
			if (hadGetPerson) {

				// Log.d("attendance", response);

				//处理请求得到的html，获取考勤信息
				new DealAttendanceInfoDataByRegular(getApplicationContext(), response);

				boolean is = nb_school_message.getBoolean("isFinAttend", true);
				//如果是第一次进入该页面，自动获取，不算刷新的，所以不弹出提示
				if (!is) {
					Toast.makeText(getApplicationContext(), "刷新完成",
							Toast.LENGTH_SHORT).show();
				}

				//保存第一次进入该页面的标记为false
				Editor editor = nb_school_message.edit();
				editor.putBoolean("isFinAttend", false);
				editor.commit();

				//在本地获取考勤信息，因为处理考勤信息时，把信息保存在本地数据库了
				GetInfo();
				//通知listview更新数据
				attendanceInfoAdapter.notifyDataSetChanged();

			} else {
				Toast.makeText(getApplicationContext(), "请求失败，请检测你的网络", Toast.LENGTH_SHORT)
						.show();
			}
			if (dialog != null) {
				dialog.dismiss();
			}
			//告诉listview刷新完成
			myListView.onRefreshComplete();
		}
	};

}
